<template>
  <div>
    <el-page-header @back="goBack" :content="$route.query.id ? '编辑资产' : '新建资产'"> </el-page-header>
    <div class="ueba-detail-main">
      <sec-form
        ref="formData"
        :ruleForm="formData.data"
        :rules="formData.rules"
        :formValidateData="formData.config"
        :optionData="optionData"
        :hideProp="formData.hideProp"
        :disabledProp="disabledProp"
      >
        <template v-slot:hiveList>
          <div class="hint">请补充"hive表"信息</div>
          <sec-table :tableData="hiveList.rows" :tableCol="hiveList.cols" :border="false"></sec-table>
          <div style="text-align: left">
            <el-button
              style="padding-bottom: 0"
              icon="el-icon-circle-plus-outline"
              size="medium"
              type="text"
              @click="addHiveList"
            >
              添加选项
            </el-button>
          </div>
        </template>
        <template v-slot:gitList>
          <sec-table :tableData="gitList.rows" :tableCol="gitList.cols" :border="false"></sec-table>
          <div style="text-align: left">
            <el-button
              style="padding-bottom: 0"
              icon="el-icon-circle-plus-outline"
              size="medium"
              type="text"
              @click="addGit"
            >
              添加选项
            </el-button>
          </div>
        </template>
        <template v-slot:odinList>
          <div class="odin-box">
            <el-popover placement="top-start" title="点击可放大查看" width="600" trigger="hover">
              <el-image style="width: 600px; height: 100px" :src="url" :preview-src-list="srcList"> </el-image>
              <el-button slot="reference" class="question" type="text" icon="el-icon-question"></el-button>
            </el-popover>
            <sec-table :tableData="odinList.rows" :tableCol="odinList.cols" :border="false"></sec-table>
            <div style="text-align: left">
              <el-button
                style="padding-bottom: 0"
                icon="el-icon-circle-plus-outline"
                size="medium"
                type="text"
                @click="addOdin"
              >
                添加选项
              </el-button>
            </div>
          </div>
        </template>
      </sec-form>
    </div>
    <el-dialog title="保存并发起审计" :visible.sync="diaShow" width="50%">
      <saveAndAudit ref="saveAndAuditRef" v-if="diaShow"></saveAndAudit>
      <span slot="footer" class="dialog-footer">
        <el-button @click="diaShow = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="confirmAudit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import baseForm from "components/formValidate/myForm";
import addOptions from "components/addOptions.vue";
import { assetAddDetailApi, bizLineByUserApi } from "api/propertyManage.js";
import saveAndAudit from "./saveAndAudit.vue";

export default {
  components: {
    baseForm,
    addOptions,
    saveAndAudit,
  },
  props: {},
  data() {
    return {
      diaShow: false,
      loading: false,
      url: require("@/assets/odin-example.png"),
      srcList: [require("@/assets/odin-example.png")],
      hiveList: {
        rows: [],
        cols: [
          { type: "text", label: "库名", prop: "dbName", placeholder: "请输入库名（hive）" },
          { type: "text", label: "表名", prop: "tableName", placeholder: "请输入hive表名（多个表之间用，隔开）" },
          {
            type: "operation",
            label: "操作",
            width: 80,
            children: [
              {
                icon: "el-icon-remove-outline",
                class: "close-btn select-line-icon",
                click: ({ row, $index }) => {
                  this.hiveList.rows.splice($index, 1);
                },
              },
            ],
          },
        ],
      },
      gitList: {
        rows: [],
        cols: [
          {
            type: "text",
            label: "git地址",
            prop: "git",
            align: "left",
            placeholder: "样例：git@git.xiaojukeji.com:devops/newmodule.git",
          },
          {
            type: "operation",
            label: "操作",
            width: 80,
            children: [
              {
                icon: "el-icon-remove-outline",
                class: "close-btn select-line-icon",
                click: ({ row, $index }) => {
                  this.gitList.rows.splice($index, 1);
                },
              },
            ],
          },
        ],
      },
      odinList: {
        rows: [],
        cols: [
          {
            type: "text",
            label: "odin地址",
            prop: "odin",
            align: "left",
            placeholder: "样例：允许英文字母、数字、中划线、下划线和点",
          },
          {
            type: "operation",
            label: "操作",
            width: 80,
            children: [
              {
                icon: "el-icon-remove-outline",
                class: "close-btn select-line-icon",
                click: ({ row, $index }) => {
                  this.odinList.rows.splice($index, 1);
                },
              },
            ],
          },
        ],
      },
      addOptions: [
        { label: "选项一", value: "选项一" },
        { label: "选项二", value: "选项二" },
      ],
      optionData: {
        pmUsers: [],
        noticeUsers: [],
        leader: [],
      },
      disabledProp: { domain: false },
      formData: {
        data: {
          source: "",
          domain: "",
          domainName: "",
          businessLineInfo: "",
          leader: "",
          dept2: "",
          scanDev: "",
          importSystem: "",
          cluster: "",
          ctCode: "",
          pmUsers: "",
          pmName: "",
          noticeUsers: [],
          extraData: "",
          remark1: "",
          //todo 业务线
          businessLineId: "",
          businessLine: "",
        },
        hideProp: { cluster: true, ctCode: true, importSystem: true },
        config: [
          { title: "基础信息" },
          {
            disabled: true,
            type: "select",
            span: 8,
            label: "资产来源",
            prop: "source",
            option: this.$store.state.dictionary[100100],
          },
          { type: "text", span: 8, label: "域名", prop: "domain", placeholder: "样例：audit.intra.xiaojukeji.com" },
          { type: "text", span: 8, label: "系统名称", prop: "domainName" },
          {
            type: "select",
            span: 8,
            clearable: true,
            filterable: true,
            label: "资产类型",
            prop: "scanDev",
            option: this.$store.state.dictionary["scanDev"],
          },
          {
            span: 8,
            type: "select",
            disabled: true,
            label: "资产级别",
            prop: "importSystem",
            option: this.$store.state.dictionary[100400],
          },
          { type: "textarea", span: 24, label: "系统简介", prop: "extraData" },
          { type: "textarea", span: 24, label: "备注", prop: "remark1" },
          { title: "权属信息" },
          {
            type: "select",
            span: 8,
            label: "权属负责人",
            prop: "leader",
            clearable: true,
            filterable: true,
            remote: true,
            change: async (e, a) => {
              let account = this.formData.data.leader.split("-")[0];

              let depInfo = await this.$store.dispatch("propertyManage/relationship", { account: account });
              let userInfo = await bizLineByUserApi({ account: account });

              this.formData.data.dept2 = depInfo?.data?.dept2 || "";
              this.formData.data.businessLine = userInfo?.data?.businessLine || "";
              this.formData.data.businessLineId = userInfo?.data?.businessLineId;
            },
            remoteMethod: async (query) => {
              //select 输入加载下拉框数据
              let res = await this.$store.dispatch("user/getSysUser", { account: query });
              var arr = [];
              res.data.forEach((e) => {
                if (e.name.search("<离职>") == -1) {
                  arr.push({
                    label: e.account + `-${e.name}`,
                    value: e.account + `-${e.name}`,
                  });
                }
              });

              this.optionData.leader = arr;
            },
          },
          { type: "text", span: 8, label: "权属部门", prop: "dept2", disabled: true },

          { type: "text", span: 8, label: "所属业务线", prop: "businessLine", disabled: true },

          {
            type: "select",
            span: 8,
            label: "PM",
            prop: "pmUsers",
            multiple: true,
            clearable: true,
            filterable: true,
            remote: true,

            remoteMethod: async (query) => {
              //select 输入加载下拉框数据
              let res = await this.$store.dispatch("user/getSysUser", { account: query });
              this.optionData.pmUsers = res.data.map((e) => {
                return {
                  label: `${e.account} - ${e.name}`,
                  value: e.account,
                };
              });
            },
          },
          {
            type: "select",
            span: 8,
            label: "项目关注人",
            prop: "noticeUsers",
            multiple: true,
            clearable: true,
            filterable: true,
            remote: true,
            remoteMethod: async (query) => {
              let res = await this.$store.dispatch("user/getSysUser", { account: query });
              this.optionData.noticeUsers = res.data.map((e) => {
                return {
                  label: `${e.account} - ${e.name}`,
                  value: e.account,
                };
              });
            },
          },
          { title: "数据资产" },
          { type: "slot", prop: "hiveList" },
          { title: "其他信息" },
          { type: "slot", prop: "gitList" },
          { type: "slot", prop: "odinList" },
          { type: "text", span: 8, label: "集群环境", prop: "cluster" },
          { type: "text", span: 8, label: "国家码", prop: "ctCode" },
          {
            type: "operation",
            style: { "text-align": "center" },
            children: [
              {
                label: "保 存",
                hide: () => {
                  return this.$route.query.type == "bpm";
                },
                type: "primary",
                click: () => {
                  //if中是验证表单有没有通过，不是提交数据
                  if (this.$refs.formData.submitForm()) {
                    //这里是提交数据
                    this.submitForm();
                  }
                },
              },
              {
                label: "保存并发起审计",
                hide: () => {
                  return this.$route.query.id;
                },
                type: "primary",
                click: () => {
                  //if中是验证表单有没有通过，不是提交数据
                  if (this.$refs.formData.submitForm()) {
                    this.submitForm(true);
                  }
                },
              },
            ],
          },
        ],
        rules: {
          source: [{ required: true, message: "请选择资产来源", trigger: "blur" }],
          domain: [
            { required: true, message: "请输入域名", trigger: "blur" },
            { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
          ],
          domainName: [{ min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }],
          leader: [
            { required: true, message: "请输入权属负责人", trigger: "blur" },
            { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
          ],
          dept2: [{ required: true, message: "请输入权属部门", trigger: "blur" }],
          scanDev: [{ required: true, message: "请选择资产类型", trigger: "blur" }],
          //businessLine: [{ required: true, message: "请选择", trigger: "blur" }],
          cluster: [{ min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }],
          ctCode: [{ min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }],
          //noticeUsers: [{ min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }],
          extraData: [{ min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur" }],
          remark1: [{ min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur" }],
        },
      },
    };
  },
  async mounted() {
    let { type, id } = this.$route.query;
    if (id && type == "bpm") {
      await assetAddDetailApi({ id: id }).then((res) => {
        console.log(res);
        this.formData.data = res.data;
        this.dataHandle();
      });
    } else if (id) {
      this.formData.data = await this.fatchData(this.$route.query.id);
      this.dataHandle();
    } else {
      // add
      this.formData.data.source = "manual";
    }
    if (id) {
      this.formData.hideProp.cluster = false;
      this.formData.hideProp.ctCode = false;
      this.formData.hideProp.importSystem = false;
      this.formData.hideProp.remark1 = false;
      this.disabledProp.domain = true;
    } else {
      this.formData.hideProp.cluster = true;
      this.formData.hideProp.ctCode = true;
      this.formData.hideProp.importSystem = true;
      this.formData.hideProp.remark1 = true;
      this.disabledProp.domain = false;
    }
  },
  methods: {
    dataHandle() {
      this.hiveList.rows = this.formData.data.hiveList;
      this.formData.data.businessLine = this.formData.data.businessLineInfo.businessLine;
      this.formData.data.businessLineId = this.formData.data.businessLineInfo.businessLineId;

      let gitList = this.formData.data.gitList;
      let odinList = this.formData.data.odinList;
      this.gitList.rows = gitList.map((item) => {
        return { git: item };
      });
      this.odinList.rows = odinList.map((item) => {
        return { odin: item };
      });
      this.formData.data.pmUsers = this.formData.data.pmUsers.map((e) => e.account);
      this.formData.data.noticeUsers = this.formData.data.noticeUsers.map((e) => e.account);
      if (this.formData.data.leader && this.formData.data.leaderName) {
        this.formData.data.leader = this.formData.data.leader + "-" + this.formData.data.leaderName;
      }
    },
    goBack() {
      this.$router.push("/property/manage");
    },
    async confirmAudit() {
      this.loading = true;
      let params = { ...this.params, ...(this.$refs?.saveAndAuditRef?.getData() || {}) };
      let res = await this.$store.dispatch("propertyManage/save", params).catch((res) => {
        this.loading = false;
      });
      console.log("[ res ] >", res);
      this.loading = false;
      let isSame = this.isDomainSame(res);

      if (isSame) return;
      if (res.code == 0) {
        this.message.state(res);
        this.goBack();
      }
    },
    //evalustion 是否发起审计，默认false，true发起审计，新增时使用
    async submitForm(evalustion) {
      let regFormat = this.gitOrOdinReg(); //前端没做校验处理
      if (!regFormat.odinFormat) {
        this.message.warning({ message: "odin地址格式填写不对" });
        return;
      }
      if (!regFormat.gitFormat) {
        this.message.warning({ message: "git地址格式填写不对" });
        return;
      }
      let params = Object.assign({}, this.formData.data);
      params["hiveList"] = this.hiveList.rows;

      if (!this.$route.query.id) {
        params.status = "create";
      }
      let temp1 = this.formData.data.leader;
      params.leader = temp1.split("-")[0];

      params.leaderName = temp1.split("-")[1];
      params.noticeUsers = this.formData.data.noticeUsers.join(",");
      if (this.formData.data.pmUsers) {
        params.pmUsers = this.formData.data.pmUsers.join(",");
      }
      params["evalustion"] = evalustion ? true : false;
      this.params = params;
      //点击的保存按钮(不展示弹框)
      if (!evalustion) {
        this.confirmAudit();
        return;
      }
      this.diaShow = true;
    },

    gitOrOdinReg() {
      let odinFormat = true;
      let gitFormat = true;
      this.formData.data.odinList = this.odinList.rows.map((item) => {
        let reg = /[a-zA-Z0-9][-a-zA-Z0-9_]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9_]{0,62})+\\.?/;
        if (reg.test(item.odin)) {
          // odinFormat = false;
        }
        return item.odin;
      });
      this.formData.data.gitList = this.gitList.rows.map((item) => {
        let reg = "^git@.*\\.git$";
        var re = new RegExp(reg);
        if (re.test(item.git)) {
          // gitFormat = false;
        }
        return item.git;
      });
      return { odinFormat, gitFormat };
    },
    //域名相同处理
    isDomainSame(res) {
      if (res.data == "域名重复") {
        const h = this.$createElement;
        this.$notify({
          title: "",
          duration: 0,
          type: "warning",
          dangerouslyUseHTMLString: true,
          message: h("div", { style: { "white-space": "break-spaces" } }, [
            "保存失败（域名已存在），当前域名资产归属责任人中没有您，如需添加，请联系\n",
            h(
              "strong",
              {
                style: "color:#409EFF",
                on: {
                  click: () => {
                    window.location.href = "dchat://im/start_conversation?name=liuxingtong";
                  },
                },
              },
              ["刘星童（liuxingtong）", "\n"],
            ),
            h(
              "strong",
              {
                style: "color:#409EFF",
                on: {
                  click: () => {
                    window.location.href = "dchat://im/start_conversation?name=mingliu";
                  },
                },
              },
              ["刘明（mingliu）"],
            ),
          ]),
        });
        return true;
      }
    },
    async fatchData(id) {
      let res = await this.$store.dispatch("propertyManage/detail", { id: id });
      return res.data;
    },
    async fatchUserList(account) {
      let res = await this.$store.dispatch("user/getSysUser", { account: account });
      return res.data;
    },
    removeSelectItem(index) {
      this.addOptions.splice(index, 1);
    },
    addHiveList() {
      this.hiveList.rows.push({
        dbName: "",
        tableName: "",
      });
    },
    addGit() {
      this.gitList.rows.push({ git: "" });
    },
    addOdin() {
      this.odinList.rows.push({ odin: "" });
    },
  },
  computed: {},
  watch: {
    "formData.data.domain": async function (newV, oldV) {
      if (!this.formData.data.leader) {
        let account = this.formData.data.leader.split("-")[0];
        let { data } = await this.$store.dispatch("propertyManage/relationship", { domain: newV });

        bizLineByUserApi({ account: account }).then((res) => {
          data.leader && (this.formData.data.leader = data.leader + "-" + data.leaderName);
          data.dept2 && (this.formData.data.dept2 = data.dept2);
          res.data.businessLine && (this.formData.data.businessLine = res.data.businessLine);
          res.data.businessLineId && (this.formData.data.businessLineId = res.data.businessLineId);
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.check-box {
  margin: 0 0 20px 20px;
}

.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
}
.select-item + .select-item {
  margin-top: 4px;
}
.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}
::v-deep .select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #f56c6c;
}
.odin-box {
  position: relative;
  ::v-deep .question {
    position: absolute;
    left: 65px;
    top: 7px;
    z-index: 999;
    font-size: 16px;
  }
}
</style>
